package com.ccb.sc.common.modules.shopkeeper.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
//psl import com.ccb.sc.common.bind.exception.BizException;
import com.ccb.sc.common.code.BizCodeFace;
import com.ccb.sc.common.code.ErrorCode;
import com.ccb.sc.common.modules.member.service.MemberService;
import com.ccb.sc.common.modules.setting.service.ISettingsService;
import com.ccb.sc.common.modules.shopkeeper.convert.ShopkeeperAuthConvert;
import com.ccb.sc.common.modules.shopkeeper.entity.ShopkeeperAuth;
import com.ccb.sc.common.modules.shopkeeper.enums.ApplyStatus;
import com.ccb.sc.common.modules.shopkeeper.mapper.ShopkeeperAuthMapper;
import com.ccb.sc.common.modules.shopkeeper.vo.ShopkeeperAuthCreateVo;
import com.ccb.sc.common.modules.shopkeeper.vo.ShopkeeperAuthVo;
import com.ccb.sc.common.util.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 店主认证信息 服务实现类
 * </p>
 *
 * @author ken
 * @since 2023-02-12
 */
@Slf4j
@Service
public class ShopkeeperAuthService extends ServiceImpl<ShopkeeperAuthMapper, ShopkeeperAuth> {

    @Autowired
    private ShopkeeperService shopkeeperService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private ShopkeeperPointsLogService shopkeeperPointsLogService;

    @Autowired
    private ISettingsService settingsService;

    public ShopkeeperAuthVo info(Long shopkeeperId) {
        ShopkeeperAuth shopkeeperAuth = findByShopkeeperId(shopkeeperId);
        return ShopkeeperAuthConvert.INSTANCE.entity2Vo(shopkeeperAuth);
    }

    public void create(Long shopkeeperId, ShopkeeperAuthCreateVo createVo) {
        // 判断身份证号是否已认证过
        /*int count = this.countByIdNo(createVo.getIdNo());
        if (count > 0) {
            //psl throw new BizException(BizCodeFace.createBizCode(ErrorCode.DATE_NULL).message("该信息已被认证，请勿更换认证信息"));
        }*/

        ShopkeeperAuth shopkeeperAuth = findByShopkeeperId(shopkeeperId);
        ShopkeeperAuth auth = ShopkeeperAuthConvert.INSTANCE.createVo2Entity(createVo);
        if (shopkeeperAuth == null) {
            /*boolean isAuth = authByAliyun(auth.getRealName(), auth.getIdNo());
            if (!isAuth) {
                //psl throw new BizException(BizCodeFace.createBizCode(ErrorCode.DATE_NULL).message("认证失败，请检查姓名和身份证号！"));
            }*/
            auth.setShopkeeperId(shopkeeperId);
            //auth.setStatus(ApplyStatus.SUCCESS);
            auth.setStatus(ApplyStatus.WAIT);
            auth.setAuditTime(LocalDateTime.now());
            this.save(auth);
            // 奖励上级阳光值
            /*ShopkeeperInviteSettingsVo settings = this.settingsService.getSettings(ShopkeeperInviteSettingsVo.class);
            if (settings != null && settings.getInviteAward() != null) {
                Shopkeeper shopkeeper = this.shopkeeperService.getById(shopkeeperId);
                Member member = this.memberService.getById(shopkeeper.getMemberId());
                if (member == null || member.getInviteId() == null || member.getInviteId() == 0) {
                    return;
                }
                Shopkeeper inviteShopkeeper = this.shopkeeperService.findByMemberId(member.getInviteId());
                if (inviteShopkeeper == null) {
                    return;
                }

                this.shopkeeperPointsLogService.award(inviteShopkeeper.getId(), new BigDecimal(settings.getInviteAward()),
                        ShopkeeperPointsLogType.INVITE, String.valueOf(auth.getId()), inviteShopkeeper.getMemberId());
            }*/

            return;
        }
        if (ApplyStatus.SUCCESS.equals(shopkeeperAuth.getStatus())) {
            //psl throw new BizException(BizCodeFace.createBizCode(ErrorCode.DATE_NULL).message("已审核成功，请勿重复提交！"));
        }
        auth.setId(shopkeeperAuth.getId());
        /*boolean isAuth = authByAliyun(auth.getRealName(), auth.getIdNo());
        if (!isAuth) {
            //psl throw new BizException(BizCodeFace.createBizCode(ErrorCode.DATE_NULL).message("认证失败，请检查姓名和身份证号！"));
        }*/
        //auth.setStatus(ApplyStatus.SUCCESS);
        auth.setStatus(ApplyStatus.WAIT);
        auth.setAuditTime(LocalDateTime.now());
        this.updateById(auth);

    }

    private boolean authByAliyun(String realName, String idNumber) {
        String host = "https://dfidveri.market.alicloudapi.com";
        String path = "/verify_id_name";
        String method = "POST";
        String appcode = "6f7d3d8ee0c14f01a69d5ea933d789ba";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("id_number", idNumber);
        bodys.put("name", realName);


        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);

            //获取response的body
            String responseStr = EntityUtils.toString(response.getEntity());
            log.info("实名认证返回消息：[{}]", responseStr);
            JSONObject responseJson = JSON.parseObject(responseStr);
            // 成功 {"status":"OK","state":1,"result_code":1,"result_message":"一致","request_id":"TID660d65ac1ebd43ff9172f82e194eef58"}
            if (Objects.equals("OK", responseJson.getString("status")) && responseJson.getInteger("state") == 1) {
                return true;
            }
        } catch (Exception e) {
            log.error("实名认证接口异常：,realName:{},idNo:{}", realName, idNumber, e);
            //psl throw new BizException(BizCodeFace.createBizCode(ErrorCode.FAIL));
        }
        return false;
    }

    public void alipayAccount(Long shopkeeperId, String alipayAccount) {
        ShopkeeperAuth shopkeeperAuth = findByShopkeeperId(shopkeeperId);
        if (shopkeeperAuth == null) {
            shopkeeperAuth = new ShopkeeperAuth();
        }
        shopkeeperAuth.setShopkeeperId(shopkeeperId);
        shopkeeperAuth.setAlipayAccount(alipayAccount);
        this.saveOrUpdate(shopkeeperAuth);
    }

    public ShopkeeperAuth findByShopkeeperId(Long shopkeeperId) {
        return this.getOne(Wrappers.<ShopkeeperAuth>lambdaQuery()
                .eq(ShopkeeperAuth::getShopkeeperId, shopkeeperId)
                .last("limit 1"));
    }

    public int countByIdNo(String idNo) {
        return (int) this.count(Wrappers.<ShopkeeperAuth>lambdaQuery()
                .eq(ShopkeeperAuth::getIdNo, idNo)
                .eq(ShopkeeperAuth::getStatus, ApplyStatus.SUCCESS));
    }
}
